<template>
  <view class="viewport">
    <view class="header" :style="{ paddingTop: safeAreaInsets!.top + 'px' }">
      <view class="left icon-left" @tap="Onleft()"></view>
      <view class="searchself icon-searchself" :class="{ Active: IsSearchSelf }" @tap="searchself">
        <text class="onlyMe"></text>
      </view>
      <view class="searchAccount">
        <picker
          @change="pickerAccountTypeChange"
          mode="selector"
          :range="accountTypeNames"
          range-key="AccountTypeName"
        >
          <text class="account">{{ curAccountTypeName.AccountTypeName }}</text></picker
        >
      </view>
      <uni-title type="h1" align="center" title="日历视图" class="text"></uni-title>
    </view>
    <view class="calendar-content">
      <view>
        <!-- 插入模式 -->
        <uni-calendar
          class="uni-calendar--hook"
          :selected="info.selected"
          :showMonth="false"
          @change="change"
          @monthSwitch="monthSwitch"
        />
      </view>
      <uni-calendar
        ref="calendar"
        class="uni-calendar--hook"
        :clear-date="true"
        :date="info.date"
        :insert="info.insert"
        :lunar="info.lunar"
        :startDate="info.startDate"
        :endDate="info.endDate"
        :range="info.range"
      />
    </view>
    <!-- 具体明细 -->
    <scroll-view enable-back-to-top scroll-y class="scroll">
      <view class="content">
        <view class="detail" v-for="dataCount in data" :key="dataCount.MonthDay">
          <view class="tip">
            <view>{{ dataCount.MonthDay }} {{ dataCount.Week }}</view>
            <view>收支:{{ dataCount.TotalAmount }}</view>
          </view>
          <view class="content" v-for="data in dataCount.Data" :key="data.ID">
            <view class="name" @tap="openPopup(data.ID)">
              <view class="circle" :class="data.GoodsIcon"></view>
              <view>{{ data.Goods }}</view>
              <view class="userName">{{ data.UserName }}</view>
              <view class="userName">{{ data.AccountTypeName }}</view>
            </view>
            <view>{{ data.Amount }}</view>
          </view>
        </view>
      </view>
    </scroll-view>
    <view>
      <!-- 普通弹窗 -->
      <uni-popup
        ref="popup"
        type="bottom"
        borderRadius="20rpx"
        background-color="#fafafa"
        @close="popup?.close()"
      >
        <view class="popup-content popup">
          <view class="pheader">
            <text class="title">账单详情</text>
            <text class="btn" @tap="OnUpdateGood">修 改</text>
            <text class="btn del" @tap="OnAlertDialog()">删 除</text>
          </view>
          <view class="content">
            <view class="Good">
              <view class="circle" :class="goodDetail?.GoodsIcon"></view>
              <view>{{ goodDetail?.Goods }}</view>
              <view class="userName">({{ goodDetail?.UserName }})</view>
              <view>{{ goodDetail?.Amount }}</view>
            </view>
            <view class="zhichu">
              <text>支出账号</text>
              <text
                >{{ goodDetail?.AccountName }}/{{ goodDetail?.AccountTypeName }}/{{
                  goodDetail?.AccountCard
                }}</text
              >
            </view>
            <view class="zhichu">
              <text>对方</text>
              <text>{{ goodDetail?.DuiFang }}</text>
            </view>
            <view class="zhichu">
              <text>来源</text>
              <text>{{ goodDetail?.Source }}</text>
            </view>
            <view class="zhichu">
              <text>时间</text>
              <text>{{ goodDetail?.DealTime }}</text>
            </view>
            <view class="zhichu">
              <text>备注</text>
              <text>{{ goodDetail?.Remark }}</text>
            </view>
          </view>
        </view>
      </uni-popup>
      <!-- 提示窗示例 -->
      <uni-popup ref="alertDialog" type="dialog">
        <uni-popup-dialog
          type="warn"
          cancelText="取消"
          confirmText="确定"
          title="通知"
          content="确定要删除么？"
          @confirm="delGood"
          @close="cancel"
        ></uni-popup-dialog>
      </uni-popup>
    </view>
  </view>
</template>
<script setup lang="ts">
import {
  DelGoodAPI,
  GetAccountTypeNameAPI,
  GetCalendarDataAPI,
  GetDetailDataAPI,
  GetGoodDetailAPI,
  GetUserAccountAPI,
  type GetDetailDataParams,
} from '@/services/detail'
import { useMemberStore } from '@/stores'
import type {
  AccountDetail,
  AccountTypeNameResponse,
  DataCount,
  GetCalendarDataRequest,
  GetCalendarDataResponse,
  UserAccount,
} from '@/types/detail'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 获取会员信息
const memberStore = useMemberStore()
const curUserAccount = ref<UserAccount>()
const userAccounts = ref<UserAccount[]>()
const goodDetail = ref<AccountDetail>()
const IsSearchSelf = ref<boolean>()
const accountTypeNames = ref<AccountTypeNameResponse[]>()
const curAccountTypeName = ref<AccountTypeNameResponse>({
  AccountTypeName: 'ALL',
})
//某天明细
const data = ref<DataCount[]>()
const form = ref<GetCalendarDataRequest>({
  Auth: '',
  UserGroup: '',
  DealYear: 0,
  DealMonth: 0,
  UserName: '',
  AccountNo: '',
})
const info = ref({
  lunar: true,
  range: false,
  insert: false,
  date: '',
  startDate: '',
  endDate: '',
  selected: ref<GetCalendarDataResponse[]>([]),
})
//选中日期事件
const dayChangeInfo = ref<GetDetailDataParams>({
  UserName: '',
  DealYear: 0,
  DealMonth: 0,
  AccountNo: '',
  Auth: '',
  DealDay: 0,
  GoodsType: '',
  Goods: '',
  InOut: 0,
  TimeScope: '',
  OrderBy: 1,
  Require: '',
  UserGroup: '',
  LoginName: '',
})
//修改商品
const OnUpdateGood = async () => {
  // await UpdateGoodAPI({
  //   ID: goodDetail.value!.ID,
  //   Auth: '07230602',
  //   AccountNo: goodDetail.value!.AccountNo,
  //   Amount: goodDetail.value!.Amount,
  //   IsNotYuSuan: goodDetail.value!.IsNotYuSuan,
  // })
  // popup.value?.close()
  // reFresh()
  uni.reLaunch({
    url:
      '/pages/NoteAcount/NoteAcount?pageType=update&id=' +
      goodDetail.value!.ID +
      '&backPage=/pages/Detail/Calendar',
  })
}
//返回
const Onleft = () => {
  uni.switchTab({ url: '/pages/Detail/Detail' })
}
onShow(async () => {
  await reFresh()
})
const orderby = async () => {
  dayChangeInfo.value.OrderBy = dayChangeInfo.value.OrderBy == 1 ? 2 : 1
  await reFresh()
}
//加载初始化
onLoad(async () => {
  if (memberStore.profile) {
    await InitUserAccount()
    await InitAccountTypeName()
    curUserAccount.value = userAccounts.value![userAccounts.value!.length - 1]
    form.value.Auth = memberStore.profile.Token
    dayChangeInfo.value.Auth = memberStore.profile.Token
    dayChangeInfo.value.UserGroup = memberStore.profile.UserGroup
    form.value.UserGroup = memberStore.profile.UserGroup
    dayChangeInfo.value.LoginName = memberStore.profile.UserName
    const currentDate = new Date()
    form.value.DealYear = currentDate.getFullYear()
    dayChangeInfo.value.DealYear = currentDate.getFullYear()
    form.value.DealMonth = currentDate.getMonth() + 1
    dayChangeInfo.value.DealMonth = currentDate.getMonth() + 1
    dayChangeInfo.value.DealDay = currentDate.getDate()
    reFresh()
    reFreshDayChange()
  }
})
//初始化账户列表
const InitUserAccount = async () => {
  if (memberStore.profile) {
    const res = await GetUserAccountAPI({
      UserName: memberStore.profile.UserName,
      Auth: memberStore.profile.Token,
      UserGroup: memberStore.profile.UserGroup,
    })
    res.result.push({
      AccountNo: '',
      UserName: '',
      AccountTypeName: 'ALL',
      AccountCard: 'ALL',
      Display: 'ALL',
      Remark: '',
    })
    userAccounts.value = res.result
  }
}
//查询自己
const searchself = async () => {
  if (IsSearchSelf.value) {
    form.value.UserName = ''
    dayChangeInfo.value.UserName = ''
    IsSearchSelf.value = !IsSearchSelf.value
  } else {
    form.value.UserName = memberStore.profile!.UserName
    dayChangeInfo.value.UserName = memberStore.profile!.UserName
    IsSearchSelf.value = !IsSearchSelf.value
  }
  reFresh()
}
//初始化账户类型列表
const InitAccountTypeName = async () => {
  if (memberStore.profile) {
    const res = await GetAccountTypeNameAPI({
      Auth: memberStore.profile.Token,
      UserGroup: memberStore.profile.UserGroup,
    })
    res.result.push({
      AccountTypeName: 'ALL',
    })
    accountTypeNames.value = res.result
  }
}
//选择账户类型
const pickerAccountTypeChange = (e: any) => {
  const index = e.detail.value as number
  curAccountTypeName.value = accountTypeNames.value![index]
  form.value.AccountNo = curAccountTypeName.value.AccountTypeName
  dayChangeInfo.value.AccountNo = curAccountTypeName.value.AccountTypeName
  reFresh()
}
//选择账户
const pickerAccountChange = (e: any) => {
  const index = e.detail.value as number
  curUserAccount.value = userAccounts.value![index]
  form.value.AccountNo = curUserAccount.value.AccountNo
  dayChangeInfo.value.AccountNo = curUserAccount.value.AccountNo
  reFresh()
}
//刷新事件
const reFresh = async () => {
  if (memberStore.profile) {
    if (form.value.Auth) {
      const res = await GetCalendarDataAPI(form.value)
      info.value.selected = res.result

      info.value.date = getDate(new Date(), -30).fullDate
      info.value.startDate = getDate(new Date(), -60).fullDate
      info.value.endDate = getDate(new Date(), 30).fullDate
      uni.showToast({ icon: 'success', title: '刷新成功' })
    }
  } else {
    uni.showToast({ icon: 'none', title: '请先登录' })
    setTimeout(() => {
      // 页面跳转
      uni.switchTab({ url: '/pages/my/my' })
    }, 500)
  }
}
/**
 * 获取任意时间
 */
const getDate = (date: Date, AddDayCount: number) => {
  if (!date) {
    date = new Date()
  }
  const dd = new Date(date)

  dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期

  const y = dd.getFullYear()
  const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期，不足10补0
  const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
  return {
    fullDate: y + '-' + m + '-' + d,
    year: y,
    month: m,
    date: d,
    day: dd.getDay(),
  }
}
//===选中具体日期事件====
const change = async (e: any) => {
  dayChangeInfo.value.DealYear = e.year
  dayChangeInfo.value.DealMonth = e.month
  dayChangeInfo.value.DealDay = e.date
  reFreshDayChange()
}
//刷新选中日期事件
const reFreshDayChange = async () => {
  if (memberStore.profile) {
    const res = await GetDetailDataAPI(dayChangeInfo.value)
    data.value = res.result
  } else {
    uni.showToast({ icon: 'none', title: '请先登录' })
    setTimeout(() => {
      // 页面跳转
      uni.switchTab({ url: '/pages/my/my' })
    }, 500)
  }
}
//选择月份事件
const monthSwitch = (e: any) => {
  form.value.DealYear = e.year
  form.value.DealMonth = e.month
  reFresh()
}
//弹出层
// uni-ui 弹出层组件
const popup = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
const openPopup = async (id: number) => {
  popup.value?.open()
  const res = await GetGoodDetailAPI({ ID: id })
  goodDetail.value = res.result
}

//提示框
const alertDialog = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
const OnAlertDialog = async () => {
  alertDialog.value?.open()
}
//确认删除
const delGood = async () => {
  await DelGoodAPI({
    ID: goodDetail.value!.ID,
    Auth: memberStore.profile!.Token,
  })
  alertDialog.value?.close()
  popup.value?.close()
  reFreshDayChange()
}
//取消
const cancel = async () => {
  alertDialog.value?.close()
}
</script>
<style lang="scss">
@import './styles/Calendar.scss';
</style>
